Vue Scroll To Element On Click : To scroll to an element in Vue.js using scrollTo()
, you can add a click event listener to the element that triggers the scroll. In the click event handler function, you can retrieve the target element using this.$refs.myElement
. Then, you can get its offsetTop position relative to the document using element.offsetTop
, and pass it as the first argument to window.scrollTo()
. This will smoothly scroll the page to the target element’s position. You may also need to subtract the height of any fixed headers or other elements that may be present on the page to ensure the correct scroll position.
How can you implement a scroll-to-element functionality in Vue.js that allows users to smoothly scroll to a specific element on the page by clicking on a button or link?
This code uses Vue.js to create a button that, when clicked, will smoothly scroll the window to a specific element on the page. The element is defined using the ref
attribute and accessed in the scrollToElement
method using $refs
. The offsetTop of the element is then used to determine the vertical position of the element on the page. The window.scrollTo
method is used to smoothly scroll the window to the desired position.\
Vue Scroll to section Example
<div id="app">
<button @click="scrollToElement">Scroll to element</button>
<div ref="myElement">
<h1>Welcome to my website!</h1>
<p>This is the content of my element.</p>
</div>
</div>
<script>
new Vue({
el: '#app',
methods: {
scrollToElement() {
const element = this.$refs.myElement;
const top = element.offsetTop;
window.scrollTo({
top: top,
behavior: 'smooth'
});
}
}
});
</script>